
import gulp from "gulp";
import path from 'path';
import fs from 'fs';
import globalLoadPlugin from 'gulp-load-plugins';
import formatter  from 'gulp-front-matter';
import del from 'del';
import runSequence from 'run-sequence';
import cleanCSS from 'gulp-clean-css';
import sourcemaps from 'gulp-sourcemaps';
import browserify from "browserify";
import source from "vinyl-source-stream";
import browserSync from 'browser-sync';
import changed from 'gulp-changed';
import htmlmin from 'gulp-htmlmin';
import sass from 'gulp-sass';
import scss from 'gulp-scss';
import autofix from 'gulp-autoprefixer';
import eslint from 'gulp-eslint';
import babel from 'gulp-babel';
import uglify from 'gulp-uglify';
import imagemin from 'gulp-imagemin';
import cache from 'gulp-cache';
import md5 from 'gulp-md5-assets';
import concat from 'gulp-concat';
import size from 'gulp-size';
import config from './gulp/pluginConfig'



const browserServer = browserSync.create();
const reload = browserServer.reload;
const plugin = globalLoadPlugin();



const THEME_NAME = 'shop-food';
const ROOT = path.resolve(`${__dirname}`,'../../../');
const THEME_ROOT = `${ROOT}/dist/themes`;
const DESTINATION = `${THEME_ROOT}/${THEME_NAME}`;




//uikit
gulp.task('uikit', cb=>{
	return gulp.src([`${ROOT}/node_modules/uikit/dist/**/*`])
		.pipe(gulp.dest('./libs/uikit'));

});

//转移fonts
gulp.task('move-fonts', cb=>{
    return gulp
        .src('./fonts/**/*')
        .pipe(changed('./dev/fonts'))
        .pipe(gulp.dest('./dev/fonts'));
});

// 转移 html --> (/dev)
gulp.task('move-html', cb=>{
	return gulp
		.src('./html/**/*.html')
		.pipe(changed('./dev'))
		.pipe(gulp.dest('./dev'));
});

// 压缩 html --> (/dist)
gulp.task('minify-html', ['move-html'], cb=>{
	return gulp
		.src('./dev/**/*.html')
		.pipe(htmlmin(config.htmlmin))
		.pipe(size({title:"min:html"}))
		.pipe(gulp.dest(DESTINATION))
		.pipe(md5(10));
});



// 编译 sass --> (/dev)
gulp.task('sass', cb=>{
	return gulp
		.src(['./scss/**/*.scss','!./scss/**/_*.scss'])
        .pipe(sourcemaps.init())
		.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
		.pipe(autofix(config.autofx))
		.pipe(size({title:"sass"}))
        .pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('./dev/css'))
		.pipe(reload({stream: true}));
});
gulp.task('scss', cb=>{
	return gulp
		.src(['./scss/**/*.scss','!./scss/**/_*.scss'])
        .pipe(sourcemaps.init())
		.pipe(scss({precision: 10}).on('error', sass.logError))
		.pipe(autofix(config.autofx))
		.pipe(size({title:"scss"}))
        .pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('./dev/css'))
		.pipe(reload({stream: true}));
});

// 压缩 css --> (/build)
gulp.task('minify-css', ['scss'], () => {
    return gulp
        .src('./dev/css/**/*.css')
        .pipe(cleanCSS(config.cleanCSS))
        .pipe(gulp.dest(`${DESTINATION}/css`))
        .pipe(md5(10, `${DESTINATION}/**/*.html`));   // 查找对应文件，替换为添加md5的文件名
})

// 编译 js --> (/dev)
gulp.task('babel-js', cb=>{
	return gulp
		.src('./src/**/*.js')
		.pipe(eslint())
		.pipe(eslint.format())  // 错误格式化输出
		.pipe(changed('./dev/scripts'))
		.pipe(babel({
            presets: ['es2015', 'stage-1']
        }))
        .pipe(size({title:'script'}))
        .pipe(gulp.dest('./dev/scripts'))
        .pipe(reload({stream: true}));
});

// 压缩js --> (/build)
gulp.task('minify-js', ['babel-js'], () => {
    return gulp
        .src('./dev/scripts/**/*.js')
        .pipe(uglify(config.uglify))
        .pipe(size({title:'min script'}))
        .pipe(gulp.dest(`${DESTINATION}/scripts`))
        .pipe(md5(10, `${DESTINATION}/*.html`));
})

// 压缩 css --> (/dist)
// 


// 清空文件夹
gulp.task('clean-dev', cb=>{
	return del(['./dev/*'], cb);
});

 // 转移 libs 插件 (libs 中引入的都是压缩后的文件)
 gulp.task('move-libs-dev', cb=>{
 	return gulp.src('./libs/**/*')
 		.pipe(size({title:"libs"}))
        .pipe(gulp.dest('./dev/libs'));
 });

 gulp.task('move-libs-build', () => {
    return gulp.src('./libs/**/*')
    	.pipe(size({title:"libs build"}))
        .pipe(gulp.dest(`${DESTINATION}/libs`))
        .pipe(md5(10, `${DESTINATION}/*.html`));
})

 // 转移图片 --> (/dev)
 gulp.task('move-img', () => {
    return gulp
        .src('./images/**/*.{png,jpg,gif,ico}')
        .pipe(changed('./dev/images'))
        .pipe(size({title:"images"}))
        .pipe(gulp.dest('./dev/images'))
        .pipe(reload({stream: true}));
});
// 压缩图片 --> (/build)
gulp.task('minify-img', ['move-img'], () => {
    return gulp
        .src('./dev/images/**/*.{png,jpg,gif,ico}')
        .pipe(cache(imagemin({
            progressive: true, 
            optimizationLevel: 5
        })))
        .pipe(size({title:"images"}))
        .pipe(gulp.dest(`${DESTINATION}/images`))
        .pipe(md5(10, `${DESTINATION}/**/*.{css,js,html,json}`));
});

// json 转移 --> (/dev)
gulp.task('move-json', () => {
    return gulp
        .src('./_data/*.json')
        .pipe(gulp.dest('./dev/_data'))
        .pipe(reload({stream: true}));
})

gulp.task('clean-build', cb=>{
	return del(`${DESTINATION}/*`,{force:true}, cb);
});
// json 转移至 build --> (/build)
gulp.task('build-json', () => {
    return gulp
        .src('./_data/*.json')
        .pipe(gulp.dest(`${DESTINATION}/_data`))
        .pipe(md5(10, `${DESTINATION}/**/*.js`));
})



/* *
 *  命令行命令
 *  编译 
 *  清空 /dev 文件夹，将 html、编译后的css、编译后的js、libs中文件、图片、json文件引入
*/
gulp.task('dev',cb=>{
	// [] 中任务是并行的，其他按照先后顺序执行
	runSequence('clean-dev', 'move-html',
		['sass','babel-js','move-libs-dev','move-fonts'], 
		'move-img', 'move-json',cb);

});




gulp.task("default", () => {
	console.log(DESTINATION);
  

});

// 测试执行
gulp.task('run',cb=>{
	// 启动Browsersync服务
	browserServer.init({
		server:{
			baseDir:'./dev/',  // 启动服务的目录 默认 index.html
			index:'index.html'  // 自定义启动文件名
		},
		// 决定Browsersync启动时自动打开的网址 external 表示 可外部打开 url, 可以在同一 wifi 下不同终端测试
		open: 'external',
		// 注入CSS改变
		injectChanges: true 
	});

	// 监听文件变化，执行相应任务
	gulp.watch('./scss/**/*.scss', ['scss']);
    gulp.watch('./fonts/**/*',['move-fonts']);
    gulp.watch('./src/**/*.js', ['babel-js']);
    gulp.watch('./images/**/*.{png,jpg,gif,ico}', ['move-img']);
    gulp.watch('./_data/*.json', ['move-json']);
    gulp.watch('./**/*.html', ['move-html']).on('change', reload);
});

/*
    压缩输出
    清空 /build 文件夹，压缩html、压缩css、压缩js、引入libs中文件、引入压缩后图片、引入json，同时添加MD5
*/
gulp.task('build', (cb) => {
    runSequence('clean-build', 'minify-html', [
        'move-fonts','minify-css', 'minify-js', 'move-libs-build'
    ], 'minify-img', 'build-json', cb)
})

// 生产版本测试
gulp.task('build-test', ['build'], () => {
    // 生产版本不允许更改文件后实时编译输出
    browserSync.init({
        server: {
            baseDir: DESTINATION
        },
        open: 'external'
    });
});




gulp.task('bundle',cb=>{
	return browserify("src/app.js")
	    .transform("babelify")
	    .bundle()
	    .pipe(source("bundle.js"))
	    .pipe(gulp.dest("dist"));
});

